/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.ext.echarts.builder.impl;

import cn.easyplatform.web.ext.ComponentHandler;
import cn.easyplatform.web.ext.echarts.ECharts;
import cn.easyplatform.web.ext.echarts.builder.TemplateUnit;
import cn.easyplatform.web.ext.echarts.lib.Option;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.ArrayUtils;

import java.util.*;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class HeatmapChartsBuilder extends AbstractChartsBuilder {

    public HeatmapChartsBuilder(String type) {
        super(type);
    }

    @Override
    public void build(ECharts charts, ComponentHandler dataHandler) {
        if (dataHandler == null) {
            build(charts.getOption(), getTemplate(charts.getTemplate()), true);
        } else if (charts.getOption().getDataset() != null) {
            createDataset(charts, dataHandler);
        } else if (charts.getQuery() != null) {
            List<Object[]> data = dataHandler.selectList0(Object[].class, charts.getDbId(), (String) charts.getQuery());
            createModel(charts, data);
        }
    }

    private void createModel(ECharts echarts, List<Object[]> model) {
        Map<String, Object> heatmap = null;
        if (echarts.getOption().getSeries() instanceof Map)
            heatmap = (Map<String, Object>) echarts.getOption().getSeries();
        else if (echarts.getOption().getSeries() instanceof List)
            heatmap = (Map<String, Object>) ((List) echarts.getOption().getSeries()).get(0);
        List<Object> data = new ArrayList<>();
        for (Object[] objs : model) {
            List<Object> row = new ArrayList<>();
            if(objs.length>2) {
                row.add(objs[0]);
                row.add(objs[1]);
                row.add(objs[2]);
            }
            data.add(row);
        }
        heatmap.put("data", data);
    }


}
